package com.sense.kukoo.biz_media.adapter.provider

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.sense.kukoo.common.R
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.repo.bean.BookItemBean
import com.sense.kukoo.common.repo.bean.MediaListItemBean
import com.sense.kukoo.biz_media.adapter.MediaListAdapter
import com.sense.kukoo.common.wiget.adapter.provider.MultiItemProvider
import com.sense.kukoo.common.wiget.adapter.viewholder.BaseViewHolder
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet

class MediaListItemProvider(
    val listener: MediaListAdapter.MediaListListener,
):
    MultiItemProvider<MediaListItemBean>() {

    private var mCurrentMusic: LocalMediaListItemBean?= null

    override fun getItemType(): Int = MediaListItemBean.TYPE_DEF

    override fun getItemLayoutId(): Int = R.layout.common_item_media_list

    override fun onBindViewHolder(viewHolder: BaseViewHolder, item: MediaListItemBean) {
        val data: BookItemBean = item.data
        //
        val root = viewHolder.getView(R.id.root)
        root.setOnClickListener {
            listener.onItemClick(item, viewHolder.adapterPosition)
        }
        //
        val tv_title = viewHolder.getView(R.id.tv_title) as TextView
        tv_title.text = data.name ?: ""
        //
        val tv_time_total = viewHolder.getView(R.id.tv_time_total) as TextView
        tv_time_total.text = calculateTime((data.duration ?: 0) *1000)
        //
        val iv_music_playing = viewHolder.getView(R.id.iv_music_playing) as ImageView
        if(data.id == (mCurrentMusic?.idOfChapter() ?: 0)){
            iv_music_playing.visibility = View.VISIBLE
            Monet.get(iv_music_playing.context)
                .load<GlideConfig>(com.sense.kukoo.common.R.mipmap.common_icon_wave_red)
                .into(iv_music_playing)
        }else{
            iv_music_playing.visibility = View.GONE
        }
    }

    private fun calculateTime(milliseconds:Int): String {
        val time: Int = milliseconds / 1000

        val minute: Int
        val second: Int
        return if (time >= 60) {
            minute = time / 60
            second = time % 60
            (if (minute < 10) "0$minute" else "" + minute) + if (second < 10) ":0$second" else ":$second"
        } else {
            second = time
            if (second < 10) {
                "00:0$second"
            } else "00:$second"
        }
    }

    fun setCurrentMusic(music: LocalMediaListItemBean){
        mCurrentMusic = music
    }
}